#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *str_str (const char *text, const char *sub)
{
    const char *p1, *p2;
    
    p1 = text;
    p2 = sub;

    while (*p1) {
        if (*p1 == *p2) {
            p1++;
            p2++;
        } else {
            if (*p2 == '\0') {
                /* find one */
                printf("Text: %s\nReturn:%s\n", text, p1 - (p2-sub));
                return ((char*)(p1 - (p2-sub)));
            } else {
                /* back walk */
                p1 = p1 + 1 - (p2-sub);
            }
            p2 = sub;
        }
    }
}


int sub_count_str (const char *text, const char *sub)
{
    const char *p1, *p2;
    int count = 0;

    p1 = text;
    p2 = sub;

    while (*p1) {
        if (*p1 == *p2) {
            p1++;
            p2++;
        } else {
            if (*p2 == '\0') {
                /* find one */
                count++;
            } else {
                /* back walk */
                p1 = p1 + 1 - (p2-sub);
            }
            p2 = sub;
        }
    }

    return count;
}


void del_str (const char *text, const char *sub)
{
    const char *p1, *p2;
    int i = 0, count = 0;
    char left[20] = { 0 };
        
    p1 = text;
    p2 = sub;

    while (*p1) {
        if (*p1 == *p2) {
            p1++;
            p2++;
        } else {
            if (*p2 == '\0') {
                /* find one */
                count++;
            } else {
                /* back walk */
                left[i++] = *(p1 - (p2-sub));
                p1 = p1 + 1 - (p2-sub);
            }
            p2 = sub;
        }
    }

    printf("Text: %s\nSub: %s\nLeft: %s\n", text, sub, left);
}


void del_chars(char* text, const char* patten)
{
    int hash[256], i = 0;
    char* p = text;
    char *dest;
      
    if (NULL == text || NULL == patten) {
        return;
    }
    
    memset(hash, 0, sizeof(hash));
    const char* pTemp = patten;
    while ('\0' != *pTemp)
    {
        hash[*pTemp] = 1;
        ++ pTemp;
    }
    
    dest = (char*)malloc(strlen(text) +1);
    memset(dest, 0, strlen(text)+1);
      
    while ('\0' != *p)
    {
        if(1 != hash[*p])
        {
            dest[i++] = *p;
        }
        ++p;
    }

    printf("Text: %s\nDest: %s\n", text, dest);
    free(dest);
    dest = NULL;
}


int main(int argc, char *argv[])
{
    char str[] = "They are students";
    char del[] = "aeiou";
    char text[] = "asdaskbaskg";
    char sub[] = "ask";

    str_str(text, sub);
    printf(">>> %s\n", strstr(text, sub));
    
    del_str(text, sub);
    del_chars(str, del);
    /* sub_count_str(text, sub); */
        
    return 0;
}

